from django.shortcuts import render
from rest_framework.generics import GenericAPIView,ListAPIView, RetrieveAPIView
from rest_framework.mixins import ListModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ReadOnlyModelViewSet, GenericViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin
from areas.serializers import AreaSerializer, SubAreaSerializer
from areas.models import Area

# 视图集改写-请求省份数据,,市或区县数据
class AreasViewSet(CacheResponseMixin,ReadOnlyModelViewSet):# 继承缓存mixin扩展做redis缓存

   # 已经设置了全局分页类,并配置,此接口不分页要关闭
    pagination_class = None
    # 因为使用的序列化器类不同和查询集合也不同,重写两个获取查询集/序列化器类
    def get_queryset(self):
        '''获取视图集所使用的查询集'''
        if self.action == 'list':
            return Area.objects.filter(parent=None)
        else:
            return Area.objects.all()
    def get_serializer_class(self):
        '''获取视图集所使用的序列化器类'''
        if self.action == 'list':
            return AreaSerializer
        else:
            return SubAreaSerializer

#
# # 请求省份数据
# # GET /areas/
# class AreasView(ListAPIView):
#     queryset = Area.objects.filter(parent=None)
#     serializer_class = AreaSerializer
#     # def get(self,request):
#     #     '''获取所哟偶省级地区的信息'''
#     #
#     #     #１查询所有省级地区的信息
#     #     areas = self.get_queryset()
#     #     # 2. 序列化数据并返回
#     #     serializer = self.get_serializer(areas,many=True)
#     #
#     #     return Response(serializer.data)
#
# # 请求城市或区县数据
# # 请求方式: GET /areas/(?P<pk>\d+)/
# class SubAreasView(RetrieveAPIView):
#     # 指定当前视图所使用的查询集
#     queryset = Area.objects.all()
#     # 指定当前视图所使用的序列化器类
#     serializer_class = SubAreaSerializer
#
#     # def get(self, request, pk):
#     #     """
#     #     获取指定地区的信息:
#     #     1. 根据pk查询指定地区的信息
#     #     2. 将地区数据序列化并返回(地区下级地区需要进行嵌套序列化)
#     #     """
#     #     # 1. 根据pk查询指定地区的信息 # 这个方法会用pk去查询某个地区的对象
#     #     area = self.get_object()
#     #
#     #     # 2. 将地区数据序列化并返回(地区下级地区需要进行嵌套序列化)
#     #     serializer = self.get_serializer(area)
#     #     return Response(serializer.data)

# POST  /addresses/

